/**
 * HTTP API Server
 * 
 * Hono-based HTTP server for CAgent Sidecar
 */

import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger as honoLogger } from 'hono/logger';
import { prettyJSON } from 'hono/pretty-json';
import { config } from '@/utils/config';
import { logger } from '@/utils/logger';
import type { ApiResponse, HealthCheckResponse } from '@/types';

// Import routes
import { agentRoutes } from './routes/agent';
import { sessionRoutes } from './routes/session';
import { toolRoutes } from './routes/tool';
import { mcpRoutes } from './routes/mcp';
import { skillsRoutes } from './routes/skills';
import { workersRoutes } from './routes/workers';
import agentsConfigRoutes from './routes/agents';
import subagentsRoutes from './routes/subagents';

/**
 * Create and configure Hono app
 */
export function createApp() {
  const app = new Hono();

  // ============================================================================
  // Middleware
  // ============================================================================

  // CORS
  if (config.enableCors) {
    app.use('/*', cors({
      origin: config.allowedOrigins,
      credentials: true,
    }));
  }

  // Logging
  app.use('/*', honoLogger((message) => {
    logger.info(message);
  }));

  // Pretty JSON
  app.use('/*', prettyJSON());

  // Error handling
  app.onError((err, c) => {
    logger.error('Request error', err);
    
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'INTERNAL_ERROR',
        message: err.message,
        details: process.env.NODE_ENV === 'development' ? err.stack : undefined,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  });

  // ============================================================================
  // Routes
  // ============================================================================

  // Health check
  app.get('/health', (c) => {
    const response: HealthCheckResponse = {
      status: 'healthy',
      version: '0.1.0',
      uptime: process.uptime(),
      timestamp: new Date().toISOString(),
    };
    return c.json(response);
  });

  // API routes
  app.route('/api/agent', agentRoutes);
  app.route('/api/session', sessionRoutes);
  app.route('/api/tools', toolRoutes);
  app.route('/api/mcp', mcpRoutes);
  app.route('/api/skills', skillsRoutes);
  app.route('/api/workers', workersRoutes);
  app.route('/api/agents', agentsConfigRoutes);
  app.route('/api/subagents', subagentsRoutes);

  // 404 handler
  app.notFound((c) => {
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'NOT_FOUND',
        message: `Route ${c.req.path} not found`,
      },
      timestamp: new Date().toISOString(),
    };
    return c.json(response, 404);
  });

  return app;
}

/**
 * Start the HTTP server
 */
export async function startServer() {
  const app = createApp();

  const server = Bun.serve({
    port: config.port,
    hostname: config.host,
    fetch: app.fetch,
    // Increase idle timeout for streaming responses (255 seconds max)
    idleTimeout: 255,
    // Development mode settings
    development: process.env.NODE_ENV === 'development',
  });

  logger.info(`🚀 CAgent Sidecar started`);
  logger.info(`📡 Server listening on http://${config.host}:${config.port}`);
  logger.info(`🔧 Environment: ${process.env.NODE_ENV || 'development'}`);
  logger.info(`🤖 Default model: ${config.defaultModel}`);
  logger.info(`⏱️  Idle timeout: 255 seconds (4m 15s)`);

  return server;
}

